<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <el-row v-show="showSearch">
       <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
        <el-form-item  label="参考组织" prop="partOrgName">
            <el-cascader v-model="state.queryForm.partOrgIds" ref="cascaderAddr1" @visible-change="handleVisibleChange" style="width: 420px" placeholder="请选择标签" @change="handleCascaderChange1"
            :props="{ value: 'id', label: 'name', children: 'children',checkStrictly: true }" :options="options1" clearable filterable>
            </el-cascader>
        </el-form-item>
        <el-form-item label="参考岗位" prop="partPostName">
        <el-select  @change="getItem1" v-model="state.queryForm.partPostIds" multiple filterable collapse-tags collapse-tags-tooltip :max-collapse-tags="3" placeholder="请选择" style="width: 240px">
          <el-option v-for="item in postList" :key="item.postsString" :label="item.postName" :value="item.postName"/>
        </el-select>
      </el-form-item>
      <el-form-item label="题型" prop="questionType">
        <el-select v-model="state.queryForm.questionType" placeholder="请选择题型">
          <el-option :label="item.label" :value="item.value" v-for="(item, index) in tkgl_topic_type" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="题干" prop="stem" >
        <el-input placeholder="请输入题干" v-model="state.queryForm.stem" />
      </el-form-item>
       <el-form-item label="专业名称" prop="zymcName">
           <el-select @change="getItem3" v-model="state.queryForm.zymcName" filterable clearable multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="3" placeholder="请选择" style="width: 240px">
               <el-option v-for="item in options2"   :key="item.zymcId" :label="item.zymcName" :value="item.zymcId"/>
           </el-select>
       </el-form-item>
       <el-form-item label="关键点" prop="keyPoint">
           <el-select @change="getItem2" v-model="state.queryForm.keyPoint" filterable multiple clearable collapse-tags collapse-tags-tooltip :max-collapse-tags="3" placeholder="请选择" style="width: 90%;">
<!--               <el-option v-for="item in keypointsListData"  :key="item.keyId" :label="item.zymcName+'-'+item.keyPoint" :value="item.keyId"/>-->
               <el-option v-for="item in keypointsListData" :key="item.keyId" :label="item.zymcName ? (item.zymcName + '-' + (item.keyPoint || '')) : ''" :value="item.keyId"/>
           </el-select>
       </el-form-item>
      <el-form-item>
        <el-button icon="search" type="primary" @click="getDataList">查询</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button icon="folder-add" type="primary" class="ml10" @click="goKszlFile(0)" v-auth="'train_tkglQuestionList_edit'">新 增</el-button>
<!--        <el-button icon="folder-add" type="primary" class="ml10" @click="formDialogRef.openDialog()" v-auth="'train_tkglQuestionList_add'">新 增</el-button>-->
        <el-button plain :disabled="multiple" icon="Delete" type="primary" v-auth="'train_tkglQuestionList_del'" @click="handleDelete(selectObjs)">删除</el-button>
        <el-button type="success" :visible.sync="centerDialogVisible" @click="addkeyPoints">批量导入</el-button>
        <el-button type="success" @click="downloadTemplate">下载模板</el-button>
      </el-form-item>
        </el-form>
      </el-row>
<!--      <el-row>-->
<!--        <div class="mb8" style="width: 100%">-->
<!--          <right-toolbar v-model:showSearch="showSearch" :export="'train_tkglQuestionList_export'" @exportExcel="exportExcel" class="ml10 mr20" style="float: right;" @queryTable="getDataList"></right-toolbar>-->
<!--        </div>-->
<!--      </el-row>-->
      <el-table :data="state.dataList" v-loading="state.loading" border :cell-style="tableStyle.cellStyle"
       :header-cell-style="tableStyle.headerCellStyle" @selection-change="selectionChangHandle" @sort-change="sortChangeHandle">
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="partPostName" label="试题岗位"  show-overflow-tooltip/>
          <el-table-column prop="questionType" label="题型">
          <template #default="scope">
            <dict-tag :options="tkgl_topic_type" :value="scope.row.questionType"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column prop="stem" label="题干"  show-overflow-tooltip/>
        <el-table-column prop="zymcName" label="专业名称"  show-overflow-tooltip/>
<!--        <el-table-column prop="zydjName" label="专业等级"  show-overflow-tooltip/>-->
        <el-table-column prop="keyPoint" label="关键点"  show-overflow-tooltip/>
        <el-table-column prop="readouts" label="资料解析"  show-overflow-tooltip/>
        <el-table-column prop="answer" label="答案" show-overflow-tooltip/>
        <el-table-column prop="difficulty" label="难易程度"/>
        <el-table-column prop="fileNameAll" label="资料名称" width="200"/>
         <el-table-column prop="createTime" label="创建时间"  width="200"/>
          <!--        <el-table-column prop="relatedInfo" label="关联资料"  show-overflow-tooltip/>-->
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button icon="edit-pen" text type="primary" v-auth="'train_tkglQuestionList_edit'" @click="goKszlFile(1,scope.row.id)">编辑</el-button>
<!--            <el-button icon="edit-pen" text type="primary" v-auth="'train_tkglQuestionList_edit'" @click="formDialogRef.openDialog(scope.row.id)">编辑</el-button>-->
            <el-button icon="delete" text type="primary" v-auth="'train_tkglQuestionList_del'" @click="handleDelete([scope.row.id])">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
    </div>
      <!-- 批量导入  -->
    <el-dialog v-model="centerDialogVisible" title="批量导入" @close="clean">
      <el-form ref="domlist" :model="keypointsform"  :rules="rules">
        <el-row :gutter="24">
           <el-col :span="12" class="mb20">
            <el-form-item label="参考组织" prop="partOrgId"  :rules="[{ required: true, message: '请选择岗位名称',trigger: 'change',}]">
                <el-cascader v-model="keypointsform.partOrgId"  ref="cascaderAddr" @visible-change="handleVisibleChange1"  style="width: 420px" placeholder="请选择标签" @change="handleCascaderChange2"
                :props="{ value: 'id', label: 'name', children: 'children',checkStrictly: true }" :options="options1" clearable filterable>
                </el-cascader>
            </el-form-item>
           </el-col>
           <el-col :span="12" class="mb20">
            <el-form-item label="参考岗位" prop="partPostName">
                <el-select  @change="getItem1" v-model="keypointsform.partPostName" filterable multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="3" placeholder="请选择" style="width: 240px">
                    <el-option v-for="item in postList" :key="item.postsString" :label="item.postName" :value="item.postName"/>
                </el-select>
            </el-form-item>
           </el-col>

<!--          <el-col :span="12" class="mb20">-->
<!--            <el-form-item label="专业名称" prop="zymcId" :rules="[{ required: true, message: '请选择专业名称',trigger: 'change',}]">-->
<!--              <el-select  @change="getItem3" v-model="keypointsform.zymcId" filterable :required="true">-->
<!--                <el-option v-for="item in options"  :key="item.zymcId" :label="item.zymcName" :value="item.zymcId"/>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12" class="mb20">-->
<!--            <el-form-item label="关键点" prop="keyId" :rules="[{ required: true, message: '请输入选择关键点',trigger: 'change',}]">-->
<!--              <el-select  @change="getItem2" v-model="keypointsform.keyId" multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="3" placeholder="请选择" style="width: 240px">-->
<!--                <el-option v-for="item in keypoints" :key="item.keyId" :label="item.keyPoint" :value="item.keyId"/>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>
      </el-form>
      <!-- 点击上传  -->
      <el-upload ref="upload" :file-list="fileList" class="upload-demo" action="actionUrl" :limit="1" :on-exceed="handleExceed" :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" :on-change="handleChange2" :auto-upload="false">
        <template #trigger>
<!--          <el-button type="primary" :disabled="keypointsform.partOrgId ==undefined ||keypointsform.partPostId.length ==0 || keypointsform.zymcId ==undefined || keypointsform.keyId.length ==0">上传</el-button>-->
          <el-button type="primary" :disabled="keypointsform.partOrgId ==undefined ||keypointsform.partPostName.length ==0">上传</el-button>
        </template>
      </el-upload>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取消</el-button>
        <el-button type="primary" :visible.sync="centerDialogVisible" @click="onSubmit1">提交</el-button>
      </span>
      </template>
    </el-dialog>
    <!-- 编辑、新增  -->
    <form-dialog ref="formDialogRef" @refresh="getDataList(false)" />

  </div>
</template>

<script setup lang="ts" name="systemTkglQuestionList">
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObjs,questionList,replace,downloadList} from "/@/api/train/tkglQuestionList";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { useDict } from '/@/hooks/dict';
import { rule } from '/@/utils/validate';
import { addList, getLevel, professionalnameList } from '/@/api/train/jnglProfessionLevel';
import { deptTree, syspost } from '/@/api/train/kszlData';
import { keypointsList } from "/@/api/train/jnglKeyPoints";
import { reactive, ref } from 'vue';
import { updateOnlyOffice, uploadSysFile, uploadSysFileData } from '/@/api/train/kszlFile';
import { ElMessage, ElMessageBox } from 'element-plus'
import mittBus from '/@/utils/mitt';
import { useRouter } from 'vue-router';
import type { UploadProps, UploadUserFile, UploadInstance, UploadRawFile  } from 'element-plus'
import { genFileId } from 'element-plus'
// import { globalFormData } from '/@/utils/global'
import file from '/@/components/Material/file';
import { getKeyPointListByZymcIds, getUsers } from '/@/api/train/ksglExamList';
import { log } from 'util';
const upload = ref<UploadInstance>()

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
const cascaderAddr = ref<InstanceType<typeof import('element-plus/es/components/cascader')>>(null);
const cascaderAddr1 = ref<InstanceType<typeof import('element-plus/es/components/cascader')>>(null);

// 定义查询字典
const centerDialogVisible = ref(false)
// 导入成功
const dialogVisible =ref(false)
const { tkgl_topic_type } = useDict('tkgl_topic_type')
const router = useRouter();
// 定义变量内容
const formDialogRef = ref()
const actionUrl = ref()
// 搜索变量
const queryRef = ref()
const showSearch = ref(true)
// 多选变量
const selectObjs = ref([]) as any
const studyGroupIds = ref([])
const studyGroupNames = ref([])
const multiple = ref(true)
const domlist = ref()
const options =reactive([{
	zymcName: '',
	zymcId: ''
}])
const formData = new FormData();
// 重置批量删除级form表单
const clean = () => {
  domlist.value.resetFields();
}
const  keypoints =reactive([{
    keyPoint: '',
    keyId:''
  }],
)
const keypointsform = reactive({
  partOrgId:[],
  partOrgName: [],
  partPostId: [],
  partPostName: [],
  postIds:[]
  // zymcId: '',
  // zymcName: '',
  // keyId: '',
  // keyPoint:''
})
const positions = reactive([{
  postname: '',
  pkPost: ''
}])
const keypointsListData = reactive([{}])
const options2 =reactive([{}])
const file1 = ref('');
const fileList = ref<UploadUserFile[]>([])
const newId = ref<string>();
const groupNames = ref([])
const groupIds = ref([])
const processedPKPosts = ref([])
const groupId = ref()
//学习组织数据
const options1 = ref<any[]>([]);
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {},
  pageList: fetchList
})
const postList =reactive([{}])
const zymcArr = ref([])
//部门主键
const pkDept = ref()
const partOrgName = ref()
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  downBlobFile,
	tableStyle
} = useTable(state)
//挂载完毕
onMounted(()=>{
	deptTreeList()
	getProfessionalName()
})
// 清空搜索条件
const resetQuery = () => {
  // 清空搜索条件
  queryRef.value?.resetFields()
  // 清空多选
  selectObjs.value = []
  getDataList()
}
function clearFiles() {
	fileList.value = [];
}

const handleCascaderChange1 = (item: any) => {
	if(item!==null){
		state.queryForm.groupIds = item.join('/')
		groupIds.value = item[item.length-1]
	}
	console.log(state.queryForm.groupIds,groupIds.value);
	state.queryForm.postIds = []
}
//学习岗位
const getPostList =  () =>{
	const num = groupId.value
	postList.length = 0
	// console.log('----',num,pkDept.value)
	syspost(num).then((res: any) => {
		Object.assign(postList, res.data)
		console.log(postList,'postList');
		postList.forEach((item,index)=>{
			const postsArray = item.postsString.split(',');
		})
	});
}
//参考组织下拉框关闭事件
const handleVisibleChange = (isVisible:any) => {
	if (!isVisible) {
		if (cascaderAddr1.value) {
			const checkedNodes = cascaderAddr1.value.getCheckedNodes(); // 输出选中的节点信息
			groupId.value = checkedNodes[0].value
		}
		getPostList()
	}
};
const handleCascaderChange2 = (item: any) => {
	if(item!==null){
		groupId.value = item[item.length-1]
		keypointsform.partOrgId = item
		console.log(keypointsform.partOrgId,'keypointsform.partOrgId');
	}
	state.queryForm.postIds = []
	keypointsform.postIds = []

};
//参考组织下拉框关闭事件
const handleVisibleChange1 = (isVisible:any) => {
	if (!isVisible) {
		if (cascaderAddr.value) {
			partOrgName.value = cascaderAddr.value.getCheckedNodes()[0].pathLabels
			const checkedNodes = cascaderAddr.value.getCheckedNodes(); // 输出选中的节点信息
			groupId.value = checkedNodes[0].value
			console.log(groupId.value,'uu');
		}
		keypointsform.partOrgName = partOrgName.value
		getPostList1()
	}
};
const getPostList1 =  () => {
	const num = groupId.value
	console.log(num,'ee');
	postList.length = 0
	// console.log('----',num,pkDept.value)
	syspost(num).then((res: any) => {
		Object.assign(postList, res.data)
		console.log(postList, 'postList');
		postList.forEach((item, index) => {
			const postsArray = item.postsString.split(',');
		})
	});
}
//跳转页面---------编辑state:1 新增state:0
const goKszlFile =(state:number,id:string) =>{
  console.log('id---------',id)
  const path = '/train/tkglBulidQuestion/index';
  const sendId1 = { state,id }
  console.log('send1-----',sendId1)
  router.push({path, query: sendId1 })
}

// 批量导入---专业名称
const addkeyPoints = async (zymcName: string) =>{
  centerDialogVisible.value = true;
  console.log('弹窗',centerDialogVisible);
  professionalnameList().then((res) => {
    options.length = 0;
    for (let index = 0; index < res.data.length; index++) {
      options.push({
        zymcName: res.data[index].zymcName,
        zymcId: res.data[index].zymcId,
      });
    }
    console.log("查询分类===>",options);
  });
}
const handleChange2 = async (file: File, fileList: any[]) => {
  formData.append('file', file.raw);;
}
// 新增批量导入
const onSubmit1 = async () => {
  const valid = await domlist.value.validate().catch(() => {});
  if (!valid) return false;
  const partOrgIds = keypointsform.partOrgId
	keypointsform.partOrgId = partOrgIds.join('/')

	keypointsform.partOrgName = partOrgName.value.join('/')
  const jsonTmp = JSON.stringify(keypointsform);
	console.log(jsonTmp,'jsonTmp');
  const blob = new Blob([jsonTmp], {
    type: 'application/json',
  });
	formData.append('info', blob);

  try {
    centerDialogVisible.value = false;
	const result = await questionList(formData);
    if (result && result.data) {
      const dataValue = result.data;
        alert('上传成功！返回的数据是：' + dataValue);
        clearFiles();
		clean()
		formData.delete('info')
    } else {
      alert('上传失败或返回结果不正确！');
        clearFiles();
		clean()
		formData.delete('info')
    }
  } catch (error) {
    alert('上传过程中发生错误：' + error.data);
		clearFiles();
		clean()
		formData.delete('info')
  } finally {
		// formData.delete('info');
		formData.delete('file');
	}
}
// const code = result.code;
    // if (code == '0') {
    //   useMessage().success('导入成功');
    // }
    // else if (code == '2') {
    //   const confirmResult = await ElMessageBox.confirm(result.msg, '提示', {
    //     confirmButtonText: '替换',
    //     cancelButtonText: '不替换',
    //     type: 'warning'
    //   }).catch(()=>{
    //     replace(false,result.data.redisKey)
    //     useMessage().error('用户选择不替换');
    //     // console.log('用户选择不替换!!!!!!!!!!!!!!!!!');
    //   });
    //   if (confirmResult === 'confirm') {
    //     try {
    //       console.log(result.data.redisKey,'result.data.redisKey');
    //       const replaceResult = await replace(true,result.data.redisKey)
    //       console.log('返回值',result.data.redisKey);
    //       console.log(replaceResult.code,'replaceResult.code');
    //       if (replaceResult.code == 0) { // 根据你的API成功状态判断
    //         useMessage().success('替换成功:'+ replaceResult.msg);
    //         // 在这里处理替换成功后的逻辑
    //       } else{
    //         useMessage().error('替换失败:' + replaceResult.msg);
    //         // 在这里处理替换失败后的逻辑
    //       }
    //     } catch (error) {
    //       // 处理替换接口调用时发生的错误
    //       console.error('替换接口调用失败：', error);
    //       useMessage().error('替换接口调用失败，请稍后再试！');
    //     }
    //   }
    // }
    // else {
    //   // 处理其他 code 的情况
    //   useMessage().error('导入失败：' + result.data);
    //   console.log('失败',result);
    // }
  // }
  // catch (error) {
  //   // console.error('接口返回错误：', error.data);
  //   // ElMessage.error('上传的文件必须全部是xlsx或xls格式!');
  // }
//   finally {
//     centerDialogVisible.value = false;
//   }
// };
// 导出excel
const exportExcel = () => {
  downBlobFile('/train/tkglQuestionList/export', Object.assign(state.queryForm, { ids: selectObjs }), 'tkglQuestionList.xlsx')
}
// 关键点
keypointsList().then((res) => {
  keypoints.length = 0;
  console.log( keypoints.length,'000');
	for (let index = 0; index < res.data.records.length; index++) {
      keypoints.push({
          keyPoint:res.data.records[index].keyPoint,
          keyId:res.data.records[index].keyId
		});
	}
	console.log("关键点查询分类===>",keypoints);
});

// 专业名称
// professionalnameList().then((res) => {
//   options.length = 0;
//   for (let index = 0; index < res.data.length; index++) {
//     options.push({
//       zymcName: res.data.records[index].zymcName,
//       zymcId: res.data.records[index].zymcId
//     });
//   }
//   console.log("查询分类===>",options);
// });

// 参与组织
const deptTreeList = async () => {
	deptTree().then((res) => {
		options1.value = res.data;
		console.log('111、、、',res.data)
	});
};
const getItem1=(val:any) =>{
	let pkPosts = []
	keypointsform.partPostId.length = 0
	postList.forEach(item => {
		for (let i = 0; i < val.length; i++) {
			if (item.postName == val[i]) {
				pkPosts.push(item.postsString)
				keypointsform.partPostId.push(item.postsString)
                console.log('val',val);
                console.log('item',item);
			}
		}
	})

    state.queryForm.partPostId = pkPosts.join(',')
    state.queryForm.partPostName = val.join(',')
}

// const  getProfessionalName = () => {
// 	professionalnameList().then((res) => {
// 		Object.assign(options2, res.data)
// 		console.log("专业名称",options2);
// 	});
// };
const getItem3=(val:any) =>{
	zymcArr.value = val
	state.queryForm.zymcId = val.join(',')
	state.queryForm.keyPoint = []
	getKeypointsList()
}
const getItem2=(val:any) =>{
	state.queryForm.keyPointId = val.join(',')
}
//专业名称
const  getProfessionalName = () => {
	professionalnameList().then((res) => {
		Object.assign(options2, res.data)
		console.log("专业名称",options2);
	});
};
const  getKeypointsList = () =>{
	keypointsListData.length = 0
	const ids = {
		zymcIds:  zymcArr.value
	}
	console.log(' queryForm----', ids)
	getKeyPointListByZymcIds(ids).then((res: any) => {
		Object.assign(keypointsListData, res.data)
	});
}

// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
  selectObjs.value = objs.map(({ id }) => id);
  multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm('此操作将永久删除');
  } catch {
    return;
  }

  try {
    await delObjs(ids);
    getDataList();
    useMessage().success('删除成功');
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};

// 下載文件
const  downloadTemplate=() =>{
    try {
      // 服务器地址拼接+文件下载接口
      let baseURL = import.meta.env.VITE_API_URL;
      window.open(baseURL+ "/train/tkglQuestionList/local/试题导入模板.xlsx")
    } catch (error) {
      console.error('下载文件时出错:', error);
      // 处理错误，例如显示一个错误消息给用户
    }
  }



const submitUpload = () => {
  upload.value!.submit()
  console.log(upload.value!.submit()),'upload.value!.submit()';
}

const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log('file, uploadFiles',file, uploadFiles)
}

const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log('uploadFile',uploadFile)
}

const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(
          `The limit is 3, you selected ${files.length} files this time, add up to ${
                  files.length + uploadFiles.length
          } totally`
  )
}

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
          `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
          () => true,
          () => false
  )
}



</script>
